<?php

namespace app\system\controller;

use app\common\controller\Excel;
use app\common\lib\Redis;
use app\common\model\Logs;
use think\Db;
use think\Exception;
use app\common\model\Rec;

class Collage extends Common
{
    protected $table = 'group_cate', $name = '拼团列表',$n_table='order_group_parent f';

    public function group_people($id){
        $list = Redis::Instance()->sMembers('group_' . $id);
        foreach ($list as &$v){
            $v = json_decode($v,true);
        }

        $this->assign('list',$list);
        return $this->fetch();
    }
    private function select()
    {
        $param = $this->request->param();
        $map = [];
        if ($param['times']) {
            $value = explode(' - ', input('times'));
            $map['create_time|update_time'] = array('between', '' . strtotime($value[0]) . ',' . strtotime($value[1]) . '');
        }
        // if ($param['group_cate_id']) {
        //     $map['id'] = $param['group_cate_id'];
        // }
        if ($param['state']) {
            $map['state'] = $param['state'];
        }
        $list = db($this->n_table)
        ->join('product p','f.product_id =p.id','left')
        ->order('id desc')
        ->field('f.*,p.title')
        ->where($map);

        return $list;
    }

    function index()
    {
        $list = $this->select()->paginate(20, false, ['query' => request()->get()]);
        $this->assign('list', $list);
        $this->assign('cate', db('group_cate')->select());
        return $this->fetch();
    }

    public function chance(){
        $this->assign('list', Db::name('config_chance')->select());
        return $this->fetch();
    }
    public function add_chance($id){
        if($this->request->isAjax()){
            $param = $this->request->post();
            $param['tp'] = $param['tp']/100;
            $sum = db('config_chance')->where('id','<>',$id)->sum('tp');
            if($sum+$param['tp'] > 1){
                return json(['status'=>-1,'message'=>'总概率超过100%，请检查']);
            }
            db('config_chance')->where('id',$id)->update($param);
            return json(['status'=>1,'message'=>'已保存']);
        }
        $info = db('config_chance')->where('id',$id)->find();
        $this->assign('info', $info);
        return $this->fetch();
    }

    function info($id,$state = '')
    {
        $where['parent'] = $id;
        $where['pay_state'] = 2;
        if($state){
            $where['state'] = $state;
        }
        $list = db('order_group')->where($where)->order('create_time desc')->select();
        $this->assign('list', $list);
        return $this->fetch();
    }

    function add($id = '')
    {
        if ($id) {
            //数据
            $info = db($this->table)->find($id);

            $images = db($this->table_images)->where(['upid' => $id])->order('id asc')->select();
            $this->assign('images', $images);
        } else {
            //默认数据
            $info = ['radio' => '0'];
        }
        $this->assign('info', $info);

        return $this->fetch();
    }

    function save($id = '')
    {
        if (request()->isPost()) {
            Db::startTrans();
            try {
                //数据
                $data = input('post.');
                $data['update_time'] = time();

                //图片数据
                unset($data['imgs']);
                $images = input('imgs/a');

                if ($id == '') {
                    //新增
                    $data['create_time'] = time();
                    $res = db($this->table)->insertGetId($data);
                    $id = $res;
                    $action = '添加';
                } else {
                    //修改
                    $res = db($this->table)->where(['id' => $id])->update($data);
                    $action = '修改';
                }
                if ($res) {
                    //保存图片
                    if ($images) {
                        $res = $this->saveImages($id, $images);
                        if ($res['status'] != '1') {
                            Db::rollback();
                            return return_message('0', '保存失败', '4');
                        }
                    }

                    //整体成功
                    Db::commit();
                    action('common/Logs/addLog', ['管理员[' . $this->admin['AdminName'] . ']' . $action . '了' . $this->name . '，' . $this->name . 'ID[' . $id . ']']);
                    return return_message('1', '保存成功');
                } else {
                    Db::rollback();
                    return return_message('0', '保存失败', '3');
                }
            } catch (Exception $e) {
                Db::rollback();
                return return_message('0', '保存失败', '2');
            }
        } else {
            return return_message('0', '保存失败', '1');
        }
    }

    /**
     * @param $id
     * @param array $images
     * @return array
     * 多图片保存
     */
    function saveImages($id, array $images)
    {
        $res = $this->createChildTableDatas($this->table_images, ['upid' => $id], $images, function ($v) use ($id) {
            return ['upid' => $id, 'img' => $v];
        });
        return $res;
    }

    function state($id, $key, $val)
    {
        return $this->editState($this->table, $id, $key, $val);
    }

    function value($id, $key, $val)
    {
        return $this->editValue($this->table, $id, $key, $val);
    }

    function export()
    {
        $excelc = new Excel();

        $map = [
            ['title' => 'title', 'key' => 'title', 'width' => '20'],
            ['title' => 'create_time', 'key' => 'create_time'],
            ['title' => '状态', 'key' => 'radio'],
        ];

        $data = $this->select()->select();
        foreach ($data as $k => &$v) {
            $v['create_time'] = date('Y-m-d', $v['create_time']);
            $v['radio'] = $v['radio'] == '1' ? '显示' : '隐藏';
        }

        $excelc->export($this->name . date('YmdHis'), $map, $data);
    }

    /** 拼团级别添加机器人 */
    public function add_robot()
    {
        $id = $this->request->param('id');
        $num = $this->request->param('num');
        if ($num > 500) return json(['code' => -1, 'msg' => '单次最多添加500机器人数']);
        //查询有没有待开的团

        for ($i = 1; $i <= $num; $i++) {
            Redis::Instance()->lpush('group_robot_' . $id, 1);
        }
        return json(['code' => 1, 'msg' => '添加成功']);
    }

    public function gold()
    {
        $list = db('config_gold')->where('is_del', 0)->select();
        $this->assign('list', $list);
        return $this->fetch();
    }

    public function add_gold($id = '')
    {
        if ($this->request->isAjax()) {
            $data = input('post.');
            $data['update_time'] = time();
            db('config_gold')->where('id', $id)->update($data);
            return return_message('1', '保存成功');
        } else {
            if ($id) {
                //数据
                $info = db('config_gold')->where('id', $id)->find($id);

            } else {
                //默认数据
                $info = ['radio' => '0'];
            }
            $this->assign('info', $info);
            return $this->fetch();
        }

    }

    function gold_state($id, $key, $val)
    {
        return $this->editState('config_gold', $id, $key, $val);
    }


    public function gold_log()
    {
        $param = $this->request->param();
        $map = [];
        if ($param['times']) {
            $value = explode(' - ', input('times'));
            $map['create_time'] = array('between', '' . strtotime($value[0]) . ',' . strtotime($value[1]) . '');
        }
        if ($param['keyword']) {
            $map['code'] = ['like', '%' . $param['keyword'] . '%'];
        }
        $list = db('member_exchange')->where($map)->order('create_time desc')->paginate(20, false, ['query' => request()->get()]);

        $this->assign('list', $list);
        return $this->fetch();
    }

    public function open_group()
    {
        $type = $this->request->param('type');
        $group = new \app\index\model\Group();
        switch ($type) {
            case 1:
                $group->open_group(input('t_id'),6);
                return json(['code'=>1,'msg'=>'操作成功']);
                break;
            case 2:
                return $group->task_win_prize(6,6);
                break;
            case 3:
                return $group->task_not_win_prize('10123',6);
                break;
            case 4:
                return $group->clear_redis();
                break;
            default:
                return json(['code' => -1, 'msg' => '加载失败']);
        }
    }
      /*检测团是否超过3分钟没完成 1分钟*/
    public function check_g_over($value='')
    {
       $res=Redis::Instance()->hGetAll('all_g_time');
       $time=time();
       $rec=new Rec();
       foreach ($res as $key => $value) {
            $arr=json_decode($value,true);
            if($arr['over_time']<$time){//到时
             $group_user=Redis::Instance()->sMembers('g_user'.$arr['g_id']);
             $rec->group_fail($key,$group_user);
             Redis::Instance()->hDel('all_g_time',$key);
             //删除库存
             Redis::Instance()->del($arr['g_id'].'_inv');
             
             //删除团内会员
             Redis::Instance()->del('g_user' .$arr['g_id']);
            // //删除团
             Redis::Instance()->del('fy_group_' . $arr['g_id']);
            }
       }
        Logs::add('后台', '管理员', '检测完成');

       return['code'=>1,'msg'=>'检测完成'];
    }
    /**
     * 待中区
     * @Author   阿文
     * @DateTime 2021-05-29T17:44:32+0800
     * @param    string                   $value [description]
     * @return   [type]                          [description]
     */
    public function wait($value='')
    {
        $param = $this->request->param();
        $map = ['luck_id'=>'0'];
        if ($param['times']) {
            $value = explode(' - ', input('times'));
            $map['create_time'] = array('between', '' . strtotime($value[0]) . ',' . strtotime($value[1]) . '');
        }
        if ($param['keyword']) {
            $map['ucode'] = ['like', '%' . $param['keyword'] . '%'];
        }
        $list = db('wait_list w')
        ->join('product_cate p', 'w.group_id=p.id', 'left')
        ->field('w.*,p.Name')->where($map)->order('id')->paginate(20, false, ['query' => request()->get()]);

        $this->assign('list', $list);
        return $this->fetch();
    }

}